import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message, Upload } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled, EyeOutlined, UploadOutlined,ExportOutlined } from '@ant-design/icons'
import { getGoodInfo, deleteGoodInfo, addGoodInfo, editGoodInfo } from "@net/good/info"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import "../../index.scss"
import Power from "@comm/power"
import moment from "moment"
import { mediator } from '@comm/mediator'

interface IPorps { }
interface IStates {
    data: any[]
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    page: number,
    pageSize: number,
    total: number,
    search: any,
    uploadProps: any
}

export default class GoodInfo extends Component<IPorps, IStates> {
    // 表格设置
    private column = [
        {
            key: "name",
            dataIndex: "name",
            title: "名称",
            align: "center",
            ellipsis: true
        },
        {
            key: "brand",
            dataIndex: "brand",
            title: "品牌",
            align: "center",
            ellipsis: true
        },
        {
            key: "code",
            dataIndex: "code",
            title: "编码",
            align: "center"
        },
        {
            key: "company",
            dataIndex: "company",
            title: "公司",
            align: "center",
            ellipsis: true
        },
        {
            key: "legalperson",
            dataIndex: "legalperson",
            title: "法定代表人",
            align: "center"
        },
        {
            key: "phone",
            dataIndex: "phone",
            title: "联系电话",
            align: "center"
        },
        {
            key: "createtime",
            dataIndex: "createtime",
            title: "创建时间",
            align: "center"
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="good:info:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="good:info:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                        <Power authKey="good:info:detail">
                            <Button size="small" icon={<EyeOutlined />}
                                onClick={() => { this.openDetail(item) }}
                                style={{ color: "#fff", backgroundColor: "#67C23A" }} />
                        </Power>
                    </div>
                )
            }
        }
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "食品名称",
                name: "name",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "食品品牌",
                name: "brand",
                rules: [
                    { required: true, message: "请输入品牌名称" }
                ],
                component: {
                    placeholder: "请输入品牌名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "公司名称",
                name: "company",
                rules: [
                    { required: true, message: "请输入公司名称" }
                ],
                component: {
                    placeholder: "请输入公司名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "法定代表人",
                name: "legalperson",
                rules: [
                    { required: true, message: "请输入法定代表人" }
                ],
                component: {
                    placeholder: "请输入法定代表人",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "联系电话",
                name: "phone",
                rules: [
                    { required: true, message: "请输入联系电话" }
                ],
                component: {
                    placeholder: "请输入联系电话",
                },
                style: { borderRadius: "5px" }
            },
            this.state.title === "食品信息添加" ?
                { type: "none" } :
                {
                    type: 'input',
                    label: "创建时间",
                    name: "createtime",
                    rules: [
                        { required: true, message: "请输入联系电话" }
                    ],
                    component: {
                        // placeholder: "请输入联系电话",
                        disabled: true,
                    },
                    style: { borderRadius: "5px" }
                }
        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "fname",
            label: "食品名称",
            component: {
                placeholder: "请输入食品名称",
            },
            style: { borderRadius: "5px" }
        },
        {
            type: 'input',
            name: "fcomp",
            label: "食品公司",
            component: {
                placeholder: "请输入食品名称",
            },
            style: { borderRadius: "5px" }
        },
        {
            type: 'datePicker',
            name: "ftime",
            label: "创建时间",
            component: {
                placeholder: "请选择创建时间",
            },
            style: { borderRadius: "5px" }
        }
    ]
    private dialogFormRef = React.createRef<FormInstance>() as any
    constructor(props: IPorps) {
        super(props)
        this.state = {
            data: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            total: 0,
            page: 1,
            pageSize: 5,
            search: null,
            uploadProps: {
                name: 'file',
                action: 'http://localhost:3009/fts/good/info/upload',
                onChange: (info: any) => {
                    if (info.file.status === 'done') {
                        if (info.file.response.status === 200) {
                            message.success(`${info.file.name} 上传成功.`);
                            this.fetchData(this.state.page, this.state.pageSize)
                        } else {
                            message.error(`${info.file.name} 上传失败.${info.file.response.msg}`);
                        }
                    } else if (info.file.status === 'error') {
                        message.error(`${info.file.name} 上传失败.`);
                    }
                },
            }
        }
    }
    public componentDidMount() {
        this.fetchData(1, 5)
    }
    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        const res = await getGoodInfo({ page, pageSize }, this.state.search)
        res.data.data.map((item: any) => {
            return item.key = item.code
        })
        this.setState({ loading: false, data: res.data.data, total: res.data.total })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    public search = (item: any) => {
        if (item.fname === undefined && item.fcomp === undefined && item.ftime === undefined) {
            this.setState({ search: null }, () => {
                this.fetchData(this.state.page, this.state.pageSize)
            })
            return
        }
        item.ftime = moment(item.ftime).format("YYYY/MM/DD")
        this.setState({ search: item }, async () => {
            const res = await getGoodInfo({ page: 1, pageSize: 5 }, this.state.search)
            const { status, msg, data, total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ data: data, total })
            }
        })

    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "食品信息添加" })
    }
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "食品信息编辑", editId: item.Id }, () => {
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id })
    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        addGoodInfo(values).then((res: any) => {
            const { msg, status } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else if (status === 200) {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.cancel()
                this.fetchData(this.state.page, this.state.pageSize)
            }
        })
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.editId
        const res = await editGoodInfo(values)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.cancel()
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public delete = async () => {
        const res = await deleteGoodInfo(this.state.delId)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false })
        this.dialogFormRef.current.resetFields()
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    public renderModal = (item?: string) => {
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public openDetail = (item: any) => {
        mediator.emit("createTab", Object.assign({}, { comCode: "goodDetail", value: "食品详情" }, item))
    }
    public renderButton() {
        return (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div>
                    <Power authKey="good:info:save">
                        <Button type="primary" onClick={() => { this.openAddDialog() }}>新增信息</Button>
                    </Power>
                </div>
                <div style={{display:"flex"}}>
                    <Power authKey="good:info:save">
                        <Upload {...this.state.uploadProps}>
                            <Button type="primary" icon={<UploadOutlined />}>导入</Button>
                        </Upload>
                    </Power>
                    <Power authKey="good:info:save">
                        <Button 
                        type="primary" 
                        style={{marginLeft:'10px'}}
                        icon={<ExportOutlined />}
                        onClick={() => {
                            window.location.href = `http://localhost:3009/fts/good/info/export?page=${this.state.page}&pageSize=${this.state.pageSize}`
                        }}
                        >导出</Button>
                    </Power>
                </div>
            </div>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="good:info:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        tableKey="goodInfoTable"
                        pageChange={this.pageChange}
                        total={this.state.total}>
                    </InfoTable>
                </Card>
                {this.state.title === "食品信息添加" ? this.renderModal("") : this.renderModal()}
            </div>
        )
    }
}